<template>
  <div class="manager-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>请选择商品分类</span>
        </div>
      </template>
      <el-cascader placeholder="请选择商品分类" clearable :options="categories" :show-all-levels="false"
                   @change="categoryChange"/>
      <!--      型号分类-->
      <el-cascader placeholder="请选择商品型号" clearable :options="type_names" :show-all-levels="false"
                   @change="typeNameChange"/>
    </el-card>
    <el-table stripe :show-summary="true" :summary-method="showSummary"
              :data="goodsShow" style="width: 100% ;height: 530px;" border>
      <el-table-column prop="category_name" label="商品分类">
        <template #default="scope">
          <span>{{ scope.row.category_name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="type_name" label="型号" sortable>
        <template #default="scope">
          <el-input type="text" clearable v-model="scope.row.type_name" v-show="scope.row.active"/>
          <span v-show="!scope.row.active">{{ scope.row.type_name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="color" label="颜色" sortable>
        <template #default="scope">
          <el-input type="text" clearable v-model="scope.row.color" v-show="scope.row.active"/>
          <span v-show="!scope.row.active">{{ scope.row.color }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="goods_name" label="名称" width="210" sortable>
        <template #default="scope">
          <el-input type="text" clearable v-model="scope.row.goods_name" v-show="scope.row.active"/>
          <span v-show="!scope.row.active">{{ scope.row.goods_name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" width="90">
        <template #default="scope">
          <el-input type="text" clearable v-model="scope.row.price" v-show="scope.row.active"/>
          <span v-show="!scope.row.active">{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="count" label="数量" width="90">
        <template #default="scope">
          <el-input type="text" clearable v-model="scope.row.count" v-show="scope.row.active"/>
          <span v-show="!scope.row.active">{{ scope.row.count }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="sell_count" label="已售" width="90" sortable>
        <template #default="scope">
          <span
              :style="{color: scope.row.count ==  scope.row.sell_count  ? 'red' : 'green'}">{{ scope.row.sell_count }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="transport" label="运费" width="90">
        <template #default="scope">
          <el-input type="text" clearable v-model="scope.row.transport" v-show="scope.row.active"/>
          <span v-show="!scope.row.active">{{ scope.row.transport }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="money" label="金额" width="100">
        <template #default="scope">
          <span>{{ scope.row.money }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" type="primary" @click="goodsUpdate(scope.row)"> 修改</el-button>
          <el-button size="small" type="danger" @click="goodsDelete(scope.row)"> 删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="result">
      <div class="result-container">
        共计进货 {{ sumResult / 100 }}
      </div>
    </div>
  </div>
</template>

<script setup>
import {h, inject, onMounted, onUpdated, reactive, ref, watch} from "vue";
import {invoke} from '@tauri-apps/api'
import {showMessage} from '@/util/index'
import * as math from 'mathjs'

// 1. 从父组件中拿到 tb_categories 里面的数据
let categories = inject("categories");

let goodies = ref([])
let goodsCount = ref(0);
let sumResult = ref(0)

let goodsShow = ref([])
let type_names = ref([])

let categoryId = ref('');


const showSummary = (param) => {
  const {columns, data} = param

  if (columns.length > 0) {
    const sums = []
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = h('div', {style: {textDecoration: 'underline'}}, [
          '金额汇总',
        ])
        return
      }
      if(column.property == 'money'){
        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => Number.isNaN(value))) {
          sums[index] = ` ${values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!Number.isNaN(value)) {
              return math.round(prev + curr,2)
            } else {
              return math.round(prev,2)
            }
          }, 0)}`
        } else {
          sums[index] = ' '
        }
      }
    })
    return sums
  }

}

const typeNameChange = e => {
  if (e) {
    goodsShow.value = goodies.value.filter(g => {
      return categoryId.value === g.category_id && e[0] === g.type_name;
    })
  } else {
    if (categoryId.value != '') {
      goodsShow.value = goodies.value.filter(g => {
        return categoryId.value === g.category_id;
      })
    } else {
      goodsShow.value = goodies.value;
    }

  }
}
const categoryChange = (e) => {
  if (e) {
    categoryId.value = e[0];
    goodsShow.value = goodies.value.filter(g => {
      return categoryId.value === g.category_id;
    })
  } else {
    goodsShow.value = goodies.value
  }

  type_names.value = [];
  let set1 = new Map();
  goodsShow.value.forEach(g => {
    set1.set(g.type_name, g.type_name);
  })
  set1.forEach((v, k) => {
    type_names.value.push({"label": k, "value": v})
  })
}


/**
 * 商品表数据悠
 * @param row 需要修改的商品行
 */
const goodsUpdate = (row) => {
  row.active = !row.active;
  if (!row.active) {
    let goods = {
      id: '',
      category_id: '',
      type_name: '',
      color: '',
      name: '',
      price: '',
      count: '',
      transport: '',
      money: ''
    }
    goods.id = row.goods_id;
    goods.id = row.goods_id;
    goods.category_id = row.category_id;
    goods.type_name = row.type_name;
    goods.color = row.color;
    goods.name = row.goods_name;
    goods.price = math.round(row.price * 100, 2)
    goods.transport = math.round(row.transport * 100, 2)
    goods.count = parseInt(row.count);
    if (goods.transport == 0) {
      goods.money = math.round(goods.price * goods.count, 2);
    } else {
      goods.money = math.round(goods.price * goods.count + goods.transport, 2);
    }
    invoke("goods_change", {goods}).then(res => {
      showMessage(res)
      get_goods_all();
    })
  }
}

/**
 * 商品表数据删除
 * @param e 包含id的goods
 */
const goodsDelete = (e) => {
  let id = e.goods_id;
  invoke("goods_del", {id}).then(res => {
    get_goods_all();
    showMessage(res)
  })
}

/**
 * 获取商品数据
 */
const get_goods_all = () => {
  invoke("get_result_all").then(res => {
    let goodses = goodies.value = JSON.parse(res);
    goodses.forEach(c => {
      c.price = math.round(c.price / 100, 2);
      c.transport = math.round(c.transport / 100, 2);
      c.money = math.round(c.money / 100, 2);
      c.active = false;
    })
    goodsShow.value = goodses
  })
  getGoodsInfo();
}
/**
 * 获取商品相关信息
 */
const getGoodsInfo = () => {
  invoke("goods_money").then(res => {
    if (res != '') {
      let info = JSON.parse(res);
      sumResult.value = info[0].value;
      goodsCount.value = info[0].count;
    }

  })
}

onMounted(() => {
  get_goods_all();

})

// 暴露 get_goods_all 方法
defineExpose({get_goods_all})
</script>

<style scoped lang="scss">
.manager-container {
  position: absolute;
  width: 100%;
  height: 100%;

  .result-container {
    width: 100%;
    text-align: center;
    height: 60px;
    line-height: 60px;
    font-size: 26px;
  }

}


</style>